<?php

namespace App\controller;

use support\Request;
use think\facade\Db;
use Exception;
use crmeb\exceptions\AdminException;

class RestBase
{
    //token
    protected $token = '';

    //设备类型
    protected $deviceType = '';

    protected $apiVersion;

    //用户 id
    protected $userId = 0;

    //用户
    protected $user;

    protected $app;

    protected $redis;

    /**
     * @var
     */
    protected $services;

    //用户类型
    protected $userType;

    protected $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac', 'wxapp', 'ios'];


    protected $request;
    // 验证失败是否抛出异常
    protected $failException = false;
    // 是否批量验证
    protected $batchValidate = false;

    /**
     * 前置操作方法列表
     * @var array $beforeActionList
     * @access protected
     */
    protected $beforeActionList = [];

    protected $wechatConfg = [];

    public function __construct()
    {
        $this->request = request();
        $this->apiVersion = $this->request->header('XX-Api-Version');
        // 用户验证初始化
        $this->_initUser();

    }

    private function _initUser()
    {
        $token = $this->request->header('Authorization');
        if (substr($token, 0, 7) === 'Bearer ') {
            $token = substr($token, 7);
        }
        if (empty($token)) {
            $token = $this->request->header('XX-Token');
        }
        $deviceType = $this->request->header('XX-Device-Type');

        if (empty($deviceType)) {
            return;
        }

        if (!in_array($deviceType, $this->allowedDeviceTypes)) {
            return;
        }

        $this->deviceType = $deviceType;

        if (empty($token)) {
            return;
        }

        $this->token = $token;

        $user = Db::name('user_token')->alias('a')
            ->field('b.*')
            ->where(['token' => $token, 'device_type' => $deviceType])
            ->join('user b', 'a.user_id = b.id')
            ->find();

        if (!empty($user)) {
            $this->user = $user;
            $this->userId = $user['id'];
            $this->userType = $user['user_type'];
        }

    }


    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        return 'json';
    }

    /**
     * 获取当前登录用户的id
     * @return array|int
     */
    public function getUserId()
    {
        if (empty($this->userId)) {
            return ['code' => 10001, 'msg' => '用户未登录'];
        }
        return $this->userId;
    }
}
